ifdef STATIC
CFLAGS  += --coverage -pg
LDFLAGS += -Lliba
else
LDFLAGS += -Llib
endif
#C flags for gcov/lcov/gprof
SRC = ..
#Directory of source file
COPY_SRC = ../../src~
#Temporary directory of sources
BIN = ../../bin
#Directory of binary files
INCLUDE = $(addprefix -I, $(addprefix $(SRC)/, $(INCLUDE_FOLDER)))
#Inclued folder
LDFLAGS += $(addprefix -l, $(HEAD))
#Library files
DIR_NAME = $(shell basename `pwd`)

RM = rm -vf
#Delete command
CP = cp -vur
#Copy command
MV = mv -vi
#Move command
MKDIR = mkdir -pv
#Make directory command


all: modules libscopy $(SOURCE).out
ifdef RELEASE
	@$(MKDIR) $(BIN)/$(DIR_NAME)
	@$(CP) $(SOURCE).out shell/*_run.sh $(BIN)/$(DIR_NAME)
ifndef STATIC
	@$(CP) lib $(BIN)/$(DIR_NAME)
endif
endif
.PHONYP:all

$(SOURCE).out exe: $(SOURCE).c lib/*.so $(addsuffix /*, $(addprefix $(SRC)/, $(INCLUDE_FOLDER)))
	@echo "**********Generate executable file***********"
ifdef RELEASE
	$(CC) $(CFLAGR) $(CFLAGD) -c $(SOURCE).c $(INCLUDE)
	$(CC) $(CFLAGR) -o $(SOURCE).out $(SOURCE).o $(LDFLAGS)
else
	$(CC) $(CFLAGS) $(CFLAGD) -c $(SOURCE).c $(INCLUDE)
	$(CC) $(CFLAGS) -o $(SOURCE).out $(SOURCE).o $(LDFLAGS)
endif
.PHONYP:exe

modules:
#Enter each subdirectory
#Call the Makefile in the subdirectory
ifdef RELEASE
	@for n in $(HEAD); do \
	( $(MAKE) CC=$(CC) CFLAGS='$(CFLAGR) $(CFLAGD)' SRC_LIST='$(SRC_LIST)' --directory=$(SRC)/$$n ) \
	done
else
	@for n in $(HEAD); do \
	( $(MAKE) CC=$(CC) CFLAGS='$(CFLAGS) $(CFLAGCOV) $(CFLAGD)' SRC_LIST='$(SRC_LIST)' --directory=$(SRC)/$$n ) \
	done;
endif
.PHONYP:modules

lib/*.so liba/*.a libscopy:
	@$(MKDIR) lib liba
	@$(CP) $(addsuffix /*.a,  $(addprefix $(SRC)/, $(HEAD))) liba/
	@$(CP) $(addsuffix /*.so, $(addprefix $(SRC)/, $(HEAD))) lib/
.PHONY: libscopy

doxygen:
	@for n in $(HEAD); do \
	( $(MAKE) SRC_LIST='$(SRC_LIST)' --directory=$(SRC)/$$n copy ) \
	done
	@$(CP) $(SRC)/include/var_struc.h $(COPY_SRC)/include
	@$(MKDIR) $(COPY_SRC)/$(DIR_NAME)
	@$(CP) $(SOURCE).c $(COPY_SRC)/$(DIR_NAME)
	@$(MV) $(COPY_SRC) ./
	@echo "*********Generate Doxygen documents**********"
	@doxygen

get:
#Generate GCOV code coverage report
	gcov $(SOURCE).c
.PHONY: get

html:
#Generate graphical GCOV code coverage report
	#Create test coverage data file
	lcov -c -d $(SRC) -o $(SOURCE).info
	#Information generated by LCOV is generated into HTML
	genhtml -o gcovdir $(SOURCE).info
.PHONYP:html

clean_all: clean
#Clean in the directory
	@$(RM) $(SOURCE).out
	@$(RM) -R lib gcovdir src~
	@$(RM) pg.png callgrind.png
	@$(RM) perf_flame.svg
	@$(RM) $(SOURCE).exe
	@$(RM) -R .vs x64 x86 Debug Release
.PHONYP:clean_all

clean:
#Clean in the subdirectory
	@for n in $(HEAD) $(HEAD_SO); do \
	( $(MAKE) --directory=$(SRC)/$$n clean ) \
	done;
	@$(RM) $(SOURCE).o
	@$(RM) -R liba
	@$(RM) *.gcov *.gcda *.gcno
	@$(RM) $(SOURCE).info gmon.out pg 
	@$(RM) callgrind.out* cachegrind.out* massif.out* memchk.log
	@$(RM) perf.*
.PHONYP:clean
